package com.macro.mall.common.config;

import com.macro.mall.common.util.MDCUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于在响应中添加traceId的拦截器
 * @author macro
 */
@Component
@RequiredArgsConstructor
public class TraceIdResponseInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(TraceIdResponseInterceptor.class);
    private final Tracer tracer;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取traceId
        String traceId = request.getHeader("traceId");
        String sTraceId = request.getHeader("sTraceId");

        // 如果请求中包含traceId，则在响应头中也添加traceId
        if (traceId != null) {
            response.setHeader("traceId", traceId);
            MDCUtil.setTraceId(traceId);
        } else {
            LOGGER.warn("请求头中未找到traceId");
        }

        // 响应头中也添加sTraceId
        Span currentSpan = tracer.currentSpan();
        if (sTraceId == null && currentSpan != null) {
            sTraceId = currentSpan.context().traceId();
        }
        if (sTraceId != null) {
            response.setHeader("sTraceId", sTraceId);
            MDCUtil.setSTraceId(sTraceId);
        }

        return true;
    }
}